(function() {
    global.wx_config = require("./config/wx.conf.json");
    var bus = (process.title.split("-bus:")[1] || "dotnar").replace(/\s+/g, "");
    // wx_config = wx_config[bus];
    // console.log(wx_config);

    var md5 = require("md5");
    const sha1 = require("sha1"); // 签名加密工具
    var AccessTokenpromises = [];
    module.exports = {
        // 字符串字典排序，用于验证signature
        checkSignature: (signature, timestamp, nonce) => {
            printData("正在验证singature：", signature, timestamp, nonce);
            var arr = new Array(wx_config.TOKEN, timestamp, nonce);
            arr.sort();
            sortMaster = Object.keys(arr).sort();
            var str = '';
            for (var i = 0; i < sortMaster.length; i++) {
                str += arr[sortMaster[i]];
            };
            str = sha1(str);
            printData("生成signature：", str);
            if (str == signature) {
                return true;
            } else {
                return false;
            };
        },
        initAccessTokenPromises: co.wrap(function*() {
            yield AccessTokenpromises;
        }),
        pushAccessTokenPromises: function(array) {
            array.constructor == Object ? array = [array] : array;
            array.length ? (array.constructor === Array) ? (
                array.map(function(item) {
                    // console.log(item)
                    AccessTokenpromises.push(co.wrap(function*() {
                        var access_token = yield $.responseFromWX("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + item.APPID + "&secret=" + item.APPSECRET, "GET", 'application/x-www-form-urlencoded');
                        wx_config[item.name].ACCESS_TOKEN = access_token;
                        printSuccess(wx_config[item.name].ACCESS_TOKEN);
                        // return wx_config
                    }));
                })
            ) : false : false;
            return AccessTokenpromises;
        },
        // 获取ACESS_TOKEN
        getAccessToken: co.wrap(function*(APPID, APPSECRET) {
            var access_token = yield $.responseFromWX("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + APPID + "&secret=" + APPSECRET, "GET", 'application/x-www-form-urlencoded');
            printSuccess('获取access_token:', access_token);
            return JSON.parse(access_token);
        }),
        // 获取素材统计
        getSourceCount: co.wrap(function*(access_token) {
            var count_obj = yield $.responseFromWX(`https://api.weixin.qq.com/cgi-bin/material/get_materialcount?access_token=${access_token}`, 'GET', 'application/x-www-form-urlencoded');
            printSuccess('获取素材统计：', count_obj);
            return JSON.parse(count_obj);
        }),
        // 获取素材列表
        getSourceList: co.wrap(function*(access_token, type, offset, count) {
            var list = yield request({
                method: 'POST',
                url: `https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=${access_token}`,
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    type: type || 'news',
                    count: count || 10,
                    offset: offset || 0
                })
            });
            printSuccess('获取素材列表', type);
            return JSON.parse(list);
        }),
        // 获取菜单
        getButtonList: co.wrap(function*(access_token) {
            var buttons = yield request({
                method: 'GET',
                url: `https://api.weixin.qq.com/cgi-bin/menu/get?access_token=${access_token}`
            });
            printSuccess('获取菜单按钮：', buttons);
            return JSON.parse(buttons);
        }),
        // 创建菜单
        createButtonList: co.wrap(function*(access_token, buttons) {
            var res = yield request({
                method: 'POST',
                url: `https://api.weixin.qq.com/cgi-bin/menu/create?access_token=${access_token}`,
                headers: {
                    'Content-Type': 'application/json'
                },
                body: (JSON.stringify(buttons))
            });
            printSuccess('创建菜单按钮：', res);
            return JSON.parse(res);
        }),
        // 获取用户列表
        getUserList: co.wrap(function*(access_token, next_openid) {
            var _users = yield request({
                method: 'GET',
                url: `https://api.weixin.qq.com/cgi-bin/user/get?access_token=${access_token}${(!next_openid||next_openid=='undefined')?'':'&next_openid='+next_openid}`
            });
            printSuccess('获取用户列表');
            return JSON.parse(_users);
        }),
        // 获取用户详情
        getUserDetail: co.wrap(function*(access_token, openid) {
            var info = yield request({
                method: 'GET',
                url: `https://api.weixin.qq.com/cgi-bin/user/info?access_token=${access_token}&openid=${openid}&lang=zh_CN `
            });
            printSuccess('获取用户信息', info);
            return JSON.parse(info);
        }),
        // 设置用户备注
        setUserRemark: co.wrap(function*(access_token, openid, remark) {
            var res = yield request({
                method: 'POST',
                url: `https://api.weixin.qq.com/cgi-bin/user/info/updateremark?access_token=${access_token}`,
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    openid: openid,
                    remark: remark
                })
            });
            printSuccess('设置用户备注名:', res);
            return JSON.parse(res);
        }),
        // 将json转为xml文档字符串
        json2xml: function(jsonDoc, message) {
            printData("正在处理json数据转xml：", jsonDoc, message);
            var temp = jsonDoc.ToUserName;
            jsonDoc.ToUserName = jsonDoc.FromUserName;
            jsonDoc.FromUserName = temp;
            jsonDoc.MsgType = message.type;
            // 删除原始创建时间
            delete jsonDoc.CreateTime;
            // 删除原始创建Id
            delete jsonDoc.MsgId;
            // 删除原始Encrypt
            delete jsonDoc.Encrypt;
            // 删除原始Content;
            delete jsonDoc.Content;
            var xmlString = "<xml>" + "<CreateTime>" + Math.ceil((new Date()).getTime() / 1000) + "</CreateTime>";
            for (key in jsonDoc) {
                xmlString += "<" + key + "><![CDATA[" + jsonDoc[key] + "]]></" + key + ">";
            };
            if (message.type == 'text') {
                xmlString += `<Content><![CDATA[${message.message}]]></Content>`;
            } else if (message.type == 'image') {
                xmlString += `<Image><MediaId><![CDATA[${message.message}]]></MediaId></Image>`;
            } else if (message.type == 'news') {
                xmlString += `<ArticleCount>1</ArticleCount>`;
                xmlString += `<Articles>
                    <item>
                    <Title><![CDATA[${message.title}]]></Title> 
                    <Description><![CDATA[${message.description||''}]]></Description>
                    <PicUrl><![CDATA[${message.picurl}]]></PicUrl>
                    <Url><![CDATA[${message.url}]]></Url>
                    </item>
                    </Articles>`;
            }
            xmlString += "</xml>";
            printSuccess("json2xml转换完成：", xmlString);
            return xmlString;
        },
        requestAccessToken: co.wrap(function*(service) {
            var access_token = yield $.responseFromWX("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + wx_config[service].APPID + "&secret=" + wx_config[service].APPSECRET, "GET", 'application/x-www-form-urlencoded');
            wx_config[service].ACCESS_TOKEN = JSON.parse(access_token);
            printSuccess(wx_config[service].ACCESS_TOKEN);
            return wx_config[service].ACCESS_TOKEN;
        }),
        // 获取支付的sign,微信签名工具，用于微信支付等重要操作
        getSign: function(json) {
            printData("正在生成sign:", json);
            var _json = json;
            var _key = _json.key;
            delete _json.key;
            // 获取json参数名的字典排序
            var ov = Object.keys(_json).sort();
            var str = '';
            // 按照字典排序将参数进行URL键值对拼接
            for (var i = 0; i < ov.length; i++) {
                i == 0 ? str += ov[i] + '=' + _json[ov[i]] :
                    str += '&' + ov[i] + '=' + _json[ov[i]];
            }
            _key ? str += "&key=" + _key : false;
            print("签名加密字符串：", str);
            var sign = md5(str.toString()).toUpperCase();
            printData("生成sign:", sign);
            return sign;
        },
        // 获取预支付的prepay_id
        getPrepayId: co.wrap(function*(jsonDoc) {
            // 将json转为xml文档字符串
            print("正在获取微信支付prepay_id:", jsonDoc);
            var _json = jsonDoc;
            var xml = "<xml>";
            for (key in _json) {
                xml += "<" + key + "><![CDATA[" + _json[key] + "]]></" + key + ">";
            };
            xml += "</xml>";
            var result = yield $.responseFromWX("https://api.mch.weixin.qq.com/pay/unifiedorder", "POST", xml);
            return result;
        }),
        // 创建按钮
        createButton: co.wrap(function*(service) {
            console.log(wx_config[service].ACCESS_TOKEN)
            var json = {
                "button": [{
                    "name": "点纳科技",
                    "type": 'view',
                    "url": 'http://dotnar.com/m.dotnar.html'
                }, {
                    "name": "样品网站",
                    "sub_button": [{
                        "type": "view",
                        "name": "精英商场",
                        "url": "http://eyclub.dotnar.com",
                        "sub_button": []
                    }, {
                        "type": "view",
                        "name": "盈砾商贸",
                        "url": "http://yingli.dotnar.com",
                        "sub_button": []
                    }, {
                        "type": "view",
                        "name": "珠宝商城",
                        "url": "http://www.i-zhubao.com/",
                        "sub_button": []
                    }]
                }, {
                    "type": "view",
                    "name": "合作共赢",
                    "url": "http://mp.weixin.qq.com/s?__biz=MjM5NTIxMjU0MQ==&tempkey=DG3%2F%2BASx9N9mYNRQJtNNt2dKnY8an8KyUpq5op053%2Fw%2Fv7wZFcQ1hezs75PCSgKHKxAF3dOLkqZbpQbp40uf1v01Hugsu45Gza%2BShCO0k4%2Fpcr%2Bb8zdejjshCRSr8V18GJ5vGowi5VjSBMfoxQR08w%3D%3D&scene=18#rd",
                    "sub_button": []
                }]
            };
            var result = yield $.responseFromWX("https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + wx_config[service].ACCESS_TOKEN.access_token, "POST", JSON.stringify(json), "application/json");
            result = JSON.parse(result);
            console.log(result)
                // result = yield result.json();
            switch (result.errcode) {
                case 0:
                    result = printSuccess("创建按钮成功");
                    break;
                default:
                    printError("创建按钮失败：", result);
                    result = returnErrorbody("创建按钮失败，请重试或联系管理员");
                    break;
            };
            return result;
        })
    };
    // function getAccessToken(){

    // }


}());